import { defineStore } from 'pinia'
import store from 'store2'
import _ from 'lodash'

const useWebsiteStore = defineStore('websiteStore', {
  state() {
    return {
      webSites: store.get('website') || [],
      filterWebSites: []
    }
  },

  actions: {
    // 添加网站
    add(item) {
      if (!this.webSites.find((webSite) => webSite.url === item.url)) {
        this.webSites.unshift(item)
        store('website', this.webSites)
      } else {
        myApi.alert('此网站已经添加')
      }
    },

    // 删除网站
    remove(index) {
      this.webSites.splice(index, 1)
      store('website', this.webSites)
    }
  },

  getters: {
    getWebsites() {
      return (keywords) => {
        if (keywords === '') {
          return this.webSites
        } else {
          return _.filter(this.webSites, (webSite) => {
            let partten = new RegExp(keywords, 'i')
            return partten.test(webSite.title)
          })
        }
      }
    }
  }
})

export default useWebsiteStore
